<template>
  <div class="bg">
    <div class="article-detail">
      <div class="article-top">
        <div class="avatar" @click="goListPage"><img :src="detailInfo.head_img || defaultAvatar" alt=""></div>
        <div class="info">
          <div class="name">
            {{ detailInfo.nick_name || '匿名' }}
            <span v-for="labelItem in detailInfo.label_list" :key="labelItem.label_id">{{labelItem.title}}</span>
          </div>
          <div class="time">{{ detailInfo.create_time }}</div>
        </div>
      </div>
      <div class="article-wrapper">
        <div class="article-wrapper-title">{{ detailInfo.title }}</div>
        <div class="article-wrapper-content">
          <!-- pre标签中不能有空格换行 -->
          <pre v-if="contentType==2">{{detailInfo.content}}</pre>
          <div v-html="detailInfo.content" v-else></div>
          <!-- <editor :tplItemData="contData"></editor> -->
        </div>
        <div class="article-wrapper-img" v-if="detailInfo.file_path">
          <img v-for="(imgPath, index) in detailInfo.file_path" :src="imgPath" alt="" :key="index" @click="imgPreview(detailInfo.file_path, imgPath)">
        </div>
        <div class="article-wrapper-icons">
          <div class="icon text-right" @click="clickCopy(detailInfo.content)">
            <div class="icon_message">
              <img src="https://img.wifenxiao.com/h5-wfx/images/community/copy1.png" alt="">
            </div>
          </div>
          <div class="icon text-right" @click="handleClickComment">
            <div class="icon_message">
              <img src="https://img.wifenxiao.com/h5-wfx/images/community/news.png" alt="">
            </div>
            <span class="num" v-if="detailInfo.child && detailInfo.child.length>0">{{detailInfo.child.length}}</span>
          </div>
          <div class="icon">
            <img class="icon_message" @click.stop="handleLike(2)" v-if="detailInfo.is_praise == 1" src="https://img.wifenxiao.com/h5-wfx/images/like.png">
            <img class="icon_message" @click.stop="handleLike(1)" v-else src="https://img.wifenxiao.com/h5-wfx/images/gary-kong-like.png">
            <span class="num">{{detailInfo.praise_points_num || 0}}</span>
          </div>
        </div>
      </div>
      <div class="article-reply" v-if="detailInfo.child && detailInfo.child.length > 0">
        <div class="article-reply-title">全部回复 <em class="after"></em></div>
        <div class="article-reply-con">
          <div
            v-for="item in detailInfo.child" :key="item.community_reply_id"
            class="reply-item">
            <div class="reply-item-left" @click="goListPage(item.community_reply_id)">
              <img :src="item.headimgurl || defaultAvatar" alt="">
            </div>
            <div class="reply-item-right">
              <span class="name">{{ item.nickname }}</span>
              <span v-if="item.reply_nick">
                <span>回复</span>
                <span class="name">{{ item.reply_nick }}</span>
              </span>
              <span class="reply">：{{ item.reply_content }}</span>
              <div class="reply-img-list" v-if="item.img_url">
                <ul>
                  <li class="img-preview" v-for="(imgurl, index) in item.img_url" :key="index">
                    <img :src="imgurl" alt="" @click="imgPreview(item.img_url, imgurl)">
                  </li>
                </ul>
              </div>
              <div class="time">{{ getLocalTime(item.create_time) }}</div>
            </div>
            <div class="reply-icon" @click="handleClickReply(item.community_reply_id)">
              <div class="icon_message">
                <img src="https://img.wifenxiao.com/h5-wfx/images/community/news.png" alt="">
              </div>
            </div>
          </div>
        </div>
      </div>


      <!--  文章中的商品 start  -->
      <div class="article-good" :class="[ !transition ? 'article-good-in' : 'article-good-out']" v-if="goodsData.length > 0" @touchmove.prevent="changeLoca">
        <div class="article-good-fixed" @click="navToDetail(goodsData[0])">
          <div class="article-good-img">
            <img :src="goodsData[0].item_img">
          </div>
          <div class="article-good-cont">
            <div class="article-good-cont-title">{{goodsData[0].title}}</div>
            <div class="article-good-cont-price" v-html="scaleGoodsPriceFn(goodsData[0].price)"></div>
          </div>
        </div>
        <div class="article-good-btn" v-if="goodsData.length > 1" @click="seeMoreGood">查看更多</div>
      </div>
      <!--  文章中的商品 end  -->

      <!--   文章中商品弹出层 start  -->
      <van-popup
        v-model="showGood"
        position="bottom"
        closeable
        round
        :style="{ height: '50%' }"
      >
        <div class="article-pop-title">文中商品</div>
        <div class="article-pop-cont">
          <div class="article-pop-cont-item" v-for="(item, index) in goodsData" :key="index">
            <div class="article-pop-img">
              <img :src="item.item_img">
            </div>
            <div class="article-pop-good-cont">
              <div class="article-pop-good-cont-title">{{item.title}}</div>
              <div class="article-pop-good-cont-price">
                <div v-html="scaleGoodsPriceFn(item.price)"></div>
                <div class="btn" @click="navToDetail(item)">购买</div>
              </div>
            </div>
          </div>
        </div>
      </van-popup>
      <!--   文章中商品弹出层 end  -->
    </div>
    <Comment ref="Comments" @reloadReply="getCommunityDetailPost"></Comment>
     <!-- 授权弹出框 -->
    <small-login ref="smalllogin"></small-login>
  </div>
</template>

<script>
/**
	 * @Author: yqe@360shop.cn
	 * @Date: 2019-10-21 18:48:09
	 * @Last Modified by: yqe@360shop.cn
	 * @Last Modified time: 2019-10-21 18:48:09
	 */
import Vue from 'vue'
import { getCommunityDetail } from '@/api/community/article'
import small from '@/smallapp/small'
import SmallLogin from '@/components/SmallLogin/smallLogin'
import { mpShare } from '@/utils/utils'
import Comment from '@/components/Comment'
import Posting from '@/components/Posting'
// import editor from '@/components/diyTpl/decoration/editor'
import { scaleGoodsPrice } from '@/utils/index.js'
import { communityPraise } from '@/api/community/video'
import { Popup } from 'vant'

Vue.use(Popup)

export default Vue.extend({
  name: 'index',
  components: {
    Comment,
    Posting,
    SmallLogin,
    // editor
  },
  data() {
    return {
      showGood: false,
      goodsData: [],
      defaultAvatar: 'https://img.wifenxiao.com/h5-wfx/images/community/default_avatar.png',
      detailInfo: {},
      postingInfo: {},
      detailId: '',
      contData: {},
      contentType: '1', // 1为富文本，2为移动端textarea发布
      transition: true,
      community_user_id: 0,
      community_user_reply_id: 0
    }
  },
  methods: {
    // 点赞和取消点赞
    handleLike(type) {
      if (!small.checkLogin()) {
        this.$refs.smalllogin.openSmallLoginPop()
        return false
      }
      this.$loadingWrap.show()
      communityPraise({
        id: this.detailInfo.community_id,
        type: 1,
        add: type
      }).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          if (type == 1) {
            this.detailInfo.is_praise = 1
            this.detailInfo.praise_points_num = Number(this.detailInfo.praise_points_num) + 1
          } else if (type == 2) {
            this.detailInfo.is_praise = 0
            this.detailInfo.praise_points_num = Number(this.detailInfo.praise_points_num) - 1
          }
        } else {
          this.$Error(res.msg)
          // msg: "你已取消过啦！"
          if (res.errorCode == 'Q00001') {
            this.detailInfo.is_praise = 0
            this.detailInfo.praise_points_num = Number(this.detailInfo.praise_points_num) - 1
          }
          // msg: "你已点赞过啦！"
          if (res.errorCode == 'Z00001') {
            this.detailInfo.is_praise = 1
            this.detailInfo.praise_points_num = Number(this.detailInfo.praise_points_num) + 1
          }
        }
      })
    },
    goListPage(community_reply_id) {
      if (community_reply_id > 0) {
        this.$JumpHref(this, 'article', { community_user_reply_id: community_reply_id })
      } else {
        this.$JumpHref(this, 'article', { community_user_id: this.community_user_id })
      }
    },
    //图片放大
    imgPreview(imgs, img){
      // TODO 小程序图片预览
      wx.previewImage({
        current: img, //当前图片地址
        urls: imgs,  //所有要预览的图片的地址集合数组形式
      })
    },
    /**
       * 获取文章详情
       */
    getCommunityDetailPost() {
      const param = { id: this.detailId }
      getCommunityDetail(param).then((res) => {
        const detailInfo = res.data
        // 如果是带标签
        if (detailInfo.content.indexOf('&lt;') >= 0 && detailInfo.content.indexOf('&gt;') >= 0) {
          this.contentType = 1
        } else {
          this.contentType = 2
        }
        detailInfo.content = this.getHtml(detailInfo.content)
        detailInfo.create_time = this.getLocalTime(detailInfo.create_time)
        this.detailInfo = detailInfo
        this.goodsData = detailInfo.item_arr

        const sid = small.globalData.shopId
        const pid = small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'
        const option = {
          title: res.data.title,
          imgUrl: res.data.file_path.length ? res.data.file_path[0] : res.data.head_img, // 分享图标
          shareParam: `sid=${sid}&pid=${pid}&detailId=${res.data.community_id}`,
        }
        mpShare(true, false, '/goodsOrder/pages/articleDetail/index', option)
      })
    },
     // 复制文案
    clickCopy(e) {
      const text = e.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n').replace(/<br\/?>/gi, '\n').replace(/<[^>/]+>/g, '').replace(/(\n)?<\/([^>]+)>/g, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ').replace(/<\/?(img)[^>]*>/gi, '').replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"\'").replace(/&quot;/g,"\"").replace(/<\/?.+?>/g,"")
      // TODO 微分销复制与小程序差别
      wx.setClipboardData({
        data: text,
        success(res) {
          wx.getClipboardData({
            success(res) {
              wx.showToast({
                title: '复制成功',
                icon: 'none',
              });
            }
          })
        }
      })
    },
      //小程序文案和图片一起保存
    copySaveImg(text, event,imgs){
      let notoast=true
      this.clickCopy(text,event,notoast)
      this.saveImg(imgs,'图片与文字保存成功')
    },
    /**
       * v-html无法转义解决办法
       */
    getHtml(desc) {
      let temp = document.createElement('div')
      temp.innerHTML = desc
      const output = temp.innerText || temp.textContent
      temp = null
      return output
    },
    /**
       * 时间戳替换为时间,24小时制
       */
    getLocalTime(nS) {
      // TODO 小程序时间戳需要13位的
      nS.length == 10 ? nS *= 1000 : ''
      const date = new Date(nS)
      const Y = this.add0(date.getFullYear())
      const M = this.add0((date.getMonth() + 1))
      const D = this.add0(date.getDate())
      const H = this.add0(date.getHours())
      const m = this.add0(date.getMinutes())
      const S = this.add0(date.getSeconds())
      const Str = `${Y}/${M}/${D} ${H}:${m}:${S}`
      return Str
      return new Date(parseInt(nS) * 1000).toLocaleString('locale', { hour12: false }).replace(/年|月/g, '-').replace(/日/g, ' ')

      /* .replace(/上午/g, '') */
    },
    add0(num) {
      return num < 10 ? `0${num}` : num
    },
    /**
       * 点击评论
       */
    handleClickComment() {
      this.$refs.Comments.dialogVisible = true
      this.$refs.Comments.commentType = 2
      this.$refs.Comments.communityId = this.detailInfo.community_id
    },

    scaleGoodsPriceFn(price) {
      return scaleGoodsPrice(price)
    },
    seeMoreGood() {
      this.showGood = true
    },

    changeLoca() {
      this.transition = false
    },

    // 点击跳转商品详情
    navToDetail(item) {
      if (this.transition) {
        this.$JumpName(this, 'item-detail', { detailId: item.item_id })
      } else {
        this.transition = true
      }
    },

    // 点击回复
    handleClickReply(id) {
      this.$refs.Comments.dialogVisible = true
      this.$refs.Comments.commentType = 2
      this.$refs.Comments.communityId = this.detailInfo.community_id
      this.$refs.Comments.communityReplyId = id
    }
  },
  mounted() {
    window.addEventListener('wxload', (query) => {
      this.detailId = this.$route.query.detailId || query.detailId

      this.community_user_id = this.detailId

      this.getCommunityDetailPost()
      small.HandleShareParams()
    })
    window.addEventListener('wxshow', () => {
      if (!small.checkLogin()) {
        this.$refs.smalllogin.openSmallLoginPop()
      }
    })
  }
})
</script>

<style lang="scss">
  @import "../../../../styles/mixin";
  .bg{
    background: #f5f5f5;
    min-height: 100vh;
  }
  .article-detail{
    padding-bottom: 90px;
    background: #fff;
    .icon_message{
      display: inline-block;
      vertical-align: top;
      width: 44px;
      img{
        width: 100%;
      }
    }
    .article-top{
      display: flex;
      padding: 30px 20px;
      font-size: 0;
      .avatar{
        width: 90px;
        height: 90px;
        overflow: hidden;
        @include alignTop;
        img{
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }
      .info{
        @include alignTop;
        margin-left: 20px;
        font-size: 28px;
        color: #333;
        width: 600px;
        margin-top: 12px;
        .name{
          span{
            display: inline-block;
            font-size: 22px;
            color: #F30C23;
            padding: 2px 10px;
            margin-left: 10px;
            margin-bottom: 10px;
            background-color: rgba(243, 12, 35, .1);
            border-radius: 200px;
          }
        }
        .time{
          font-size: 24px;
          color: #999;
          margin-top: 10px;
        }
      }
    }
    .article-wrapper{
      padding:0 20px;
      &-title{
        font-size: 36px;
        color: #333;
        margin: 5px 0 10px;
      }
      &-content{
        font-size: 30px;
        line-height: 48px;
        pre{
          word-break: break-all;
          white-space: pre-wrap;
          font-size: 30px;
          font-family: -apple-system,BlinkMacSystemFont,'Helvetica Neue',Helvetica,Segoe UI,Arial,Roboto,'PingFang SC','Hiragino Sans GB','Microsoft Yahei',sans-serif;
          line-height: 48px;
        }
      }
      &-img{
        max-width: 100%;
        img{
          width: 100%;
        }
      }
      &-icons{
        text-align: right;
        color: #666;
        padding: 20px;
        .icon{
          font-size: 40px;
          @include alignTop;
          &.text-right {
            margin-right: 10px;
          }
        }
        .num{
          line-height: 34px;
          font-size: 26px;
          color: #999;
          @include alignTop;
          margin-top: 7px;
          margin-left: 0;
        }
      }
    }
    .article-reply{
      &-title{
        height: 100px;
        line-height: 100px;
        text-indent: 30px;
        border: 2px solid #dbdde3;
        border-width: 2px 0;
        background-color: #fff;
        font-weight: 400;
        font-size: 28px;
        color: #717171;
        position: relative;
        em.after{
          display: inline-block;
          position: absolute;
          bottom: -11px;
          left: 72px;
          width: 20px;
          height: 20px;
          background-color: #FAFAFA;
          transform: rotate(-135deg);
          -webkit-transform: rotate(-135deg);
          border: 2px solid #dbdde3;
          border-width: 0 2px 2px 0;
        }
      }
      &-con{
        background-color: #fbfbfb;
        padding: 10px 30px 3px;
        .reply-item{
          position: relative;
          border-bottom: 2px solid #dbdde3;
          padding: 20px 0;
          &-left{
            @include alignTop;
            overflow: hidden;
            padding-top: 16px;
            padding-right: 4px;
            img{
              width: 40px;
              height: 40px;
              border-radius: 50%;
            }
          }
          &-right{
            @include alignTop;
            width: 620px;
            span{
              display: inline-block;
              line-height: 40px;
              word-break: break-all;
              font-size: 26px;
              &.name{
                color: #5698d1;
              }
            }
            .time{
              color: #666;
              font-size: 24px;
              margin-top: 20px;
            }
          }
          .reply-icon{
            position: absolute;
            font-size: 46px;
            right: 0;
            top: 30px;
            color: #666;
          }
          .img-preview{
            overflow:hidden;
            display:inline-block;
            width: 120px;
            height: 120px;
            margin: 12px 20px 12px 0;
            padding: 0;
            vertical-align: top;
            background-color: #fff;
            img{
              width: 100%;
              border-radius: 3px;
            }
          }
        }
      }
    }

    .article-good {
      position: fixed;
      left: 22px;
      bottom: 92px;
      background: rgba(0,0,0,0.78);
      border-radius: 8px;
      padding: 16px 14px;
      &-fixed {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
      }
      &-btn {
        margin-top: 20px;
        text-align: center;
        color: #fff;
        padding: 12px 0;
        background: #ff4949;
        border-radius: 24px;
      }
      &-img {
        width: 96px;
        height: 96px;
        margin-right: 14px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }
      &-cont {
        &-title {
          width: 196px;
          height: 48px;
          color: #ffffff;
          margin-bottom: 10px;
          @include lineClamp(24px,1.4,2);
        }
        &-price {
          color: #FF3C3D;
        }
      }
    }
    .article-pop-title {
      width: 100%;
      text-align: center;
      padding: 30px 0;
      font-weight: 500;
      font-size: 32px;
    }
    .article-pop-cont {
      height: calc(100% - 100px);
      overflow-y: scroll;
      padding: 0 32px;
      box-sizing: border-box;
      &-item {
        padding: 22px 0;
        border-bottom: 1px solid #ececec;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
        &:first-child {
          padding-top: 0;
        }
        &:last-child {
          border: 0;
        }
        .article-pop-img {
          width: 190px;
          height: 190px;
          margin-right: 10px;
          img {
            width: 100%;
            height: 100%;
            border-radius: 8px;
          }
        }
        .article-pop-good-cont {
          width: calc(100% - 200px);
          &-title {
            font-size: 28px;
            height: 80px;
            line-height: 40px;
            font-weight: 400;
            overflow: hidden;
            text-overflow: ellipsis;
            display:-webkit-box;
            -webkit-box-orient:vertical;
            -webkit-line-clamp:2;
          }
          &-price {
            display: flex;
            flex-direction: row;
            flex-wrap: nowrap;
            justify-content: space-between;
            margin-top: 60px;
            line-height: 46px;
            .btn {
              font-size: 24px;
              line-height: 24px;
              font-weight: 400;
              color: #fff;
              padding: 12px 40px;
              background: #ee0a24;
              border-radius: 25px;
            }
          }
        }
      }
    }
  }
</style>
